<!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webgl - glTF loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <link type="text/css" rel="stylesheet" href="./css/main.css?2=1">
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/lhgdialog/lhgcore.lhgdialog.min.js"></script>
</head>

<body style="background: #fff">
<iframe src="menu.html"
        class="curifrme"
        frameborder="none"
></iframe>
<style>
    .color{
        background: #130AF2;
        width: 30px;
        height: 30px;
        border-radius: 4px;
        margin: 10px;
    }
</style>
<div style="position: absolute; top: 0px;right:10px">
    <div class="color" style="background:#E8C279" ></div>
    <div class="color" style="background:#130AF2 " ></div>
    <div class="color" style="background:#C5B49A " ></div>
    <div class="color" style="background:#6A5ACD " ></div>
    <div class="color" style="background:#AA4631 " ></div>
</div>


<script type="module">

    import * as THREE from './build/three.module.js';

    import Stats from './threejs/jsm/libs/stats.module.js';
    // 制作一个地板
    import { EffectComposer } from './threejs/jsm/postprocessing/EffectComposer.js';
    import { RenderPass } from './threejs/jsm/postprocessing/RenderPass.js';
    import { OutlinePass  } from './threejs/jsm/postprocessing/OutlinePass.js';
    import {PlaneGeometry, MeshPhongMaterial, Mesh} from './build/three.module.js';
    import { OrbitControls } from './threejs/jsm/controls/OrbitControls.js';
    import { GLTFLoader } from './threejs/jsm/loaders/GLTFLoader.js';
    import { RGBELoader } from './threejs/jsm/loaders/RGBELoader.js';
    import { RoughnessMipmapper } from './threejs/jsm/utils/RoughnessMipmapper.js';
    import { AfterimagePass } from './threejs/jsm/postprocessing/AfterimagePass.js';
    import { SobelOperatorShader } from './threejs/jsm/shaders/SobelOperatorShader.js';
    import { ShaderPass } from './threejs/jsm/postprocessing/ShaderPass.js';
    import { GUI } from './threejs/jsm/libs/dat.gui.module.js';
    import { UnrealBloomPass } from './threejs/jsm/postprocessing/UnrealBloomPass.js';
    const params = {
        exposure: 0.2,
        bloomStrength: 0.5,
        bloomThreshold: 0,
        bloomRadius: 0
    };

    import {
        DirectionalLight,
        DirectionalLightHelper,
        HemisphereLight,
        HemisphereLightHelper
    } from './build/three.module.js';



    let gltfpath ='./gltf/jp/'
    let gltfurl ="scene.gltf"


    let changAll  = []

    // Helper为灯关的辅助线方便调试

    //射线检测

    let colorIndex =0
    let colorArr =["#E8C279","#130AF2","#C5B49A","#6A5ACD","#AA4631"]

    //	color: 0x77F28F,



    let oldSelect,oldMaterial;
    let cameraZ=100
    let camera, scene,gui, renderer,floor,directionalLight,gltfobj,controls,stats,composerAll;

    init();
    //doinitLight()
    dolight()
    //dodiban()
    //	doAxsHelper()
    render();

    $(function(){

        $(".color").click(function(){

            colorIndex=$(this).index()
        })

    })
    // // 初始化灯光
    // function doinitLight() {
    // 	var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.3 );//模拟远处类似太阳的光源
    // 	directionalLight.color.setHSL( 0.1, 1, 0.95 );
    // 	directionalLight.position.set( 0, 200, 0).normalize();
    // 	scene.add( directionalLight );
    //
    // 	var ambient = new THREE.AmbientLight( 0x404040 ); //AmbientLight,影响整个场景的光源
    // 	ambient.position.set(30,30,30);
    // 	scene.add( ambient );
    // }
    function dolight(){

        directionalLight = new DirectionalLight(0xffffff,1);
     //   directionalLight.position.set(-4, 8, 4);


        let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff,0.5);

        scene.add(directionalLight);
        scene.add(hemisphereLight);
        // let dhelper = new DirectionalLightHelper(directionalLight, 5, 0xff0000);
        //
        //
        // hemisphereLight.position.set(0, 8, 0);
        // let hHelper = new HemisphereLightHelper(hemisphereLight, 5);
        //
        //
        //
        //
        // // 光源开启阴影
        // directionalLight.castShadow = true;
        // directionalLight.shadow.mapSize = new THREE.Vector2(1024, 1024);

    }
    function doAxsHelper(){

        let axs  = new THREE.AxesHelper(1000)
        scene.add(axs)
    }

    function init() {
        dostats()

        const container = document.createElement( 'div' );
        document.body.appendChild( container );

        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
       camera.position.set( -10, 8, cameraZ);
        scene = new THREE.Scene();
        //全局部件颜色改为白色
   //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})


        let i = 0
        // scene.background=new THREE.Color( "#353535" );
        const loader = new GLTFLoader().setPath(gltfpath );
        loader.load( gltfurl, function ( gltf ) {
            console.log(gltf.scene)

            gltfobj=gltf
            let iik=0




            gltf.scene.traverse( function ( child ) {

                if ( child.isMesh ) {

                   child.castShadow = true;
                   child.receiveShadow = true;
                   if(iik==0){

                   }
                    // 使用材料自身的颜色  在无管线的情况下  自行发光
                  // child.material.emissive =  child.material.color;
                //   child.material.emissive =  child.material.color;
                //   child.material.emissiveMap = child.material.map ;
                    // TOFIX RoughnessMipmapper seems to be broken with WebGL 2.0
                    // roughnessMipmapper.generateMipmaps( child.material );
                    const   box = new THREE.Box3().setFromObject(child)

                    const  centert= box.getCenter(new THREE.Vector3());
                    //#console.log("center")
                    //	#console.log(centert)

                    i=i+1

                }

            } );
             dobujian(gltf)


            //gltf.scene.scale.set(0.3,0.3,0.3)
            // gltf.scene.position.z=200
            // gltf.scene.position.x=200
            // gltf.scene.position.y=10

            scene.add( gltf.scene );


            render();

        } );

        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;

        // 首先渲染器开启阴影
        renderer.shadowMap.enabled = true;

        // 模型Mesh开启阴影
        container.appendChild( renderer.domElement );




        const renderScene = new RenderPass( scene, camera );


        composerAll = new EffectComposer( renderer );
        composerAll.addPass( renderScene );


        const pmremGenerator = new THREE.PMREMGenerator( renderer );
        pmremGenerator.compileEquirectangularShader();

        controls = new OrbitControls( camera, renderer.domElement );
        controls.addEventListener( 'change', render ); // use if there is no animation loop
        window.addEventListener( 'click', onDocumentMouseDown ); // use if there is no animation loop

        controls.autoRotate = true;//是否自动旋转
        controls.autoRotateSpeed = 0.5;//自动旋转速度，正比
        controls.update();

        window.addEventListener( 'resize', onWindowResize, false );
    }





    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

        render();

    }


    var projector =new THREE.Raycaster()
    function onDocumentMouseDown(event){
        return
        let objectss =[]
        let mouse = new THREE.Vector2();
        console.log(scene)
        //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义
        let x = (event.clientX / window.innerWidth) * 2 - 1;
        let y = -(event.clientY / window.innerHeight) * 2 + 1;
        //新建一个三维单位向量 假设z方向就是0.5
        //根据照相机，把这个向量转换到视点坐标系
        var vector = new THREE.Vector3(x, y,0.5).unproject(camera);

        //在视点坐标系中形成射线,射线的起点向量是照相机， 射线的方向向量是照相机到点击的点，这个向量应该归一标准化。
        var raycaster = new THREE.Raycaster(mouse, camera);


        scene.group.forEach(child=>{
            console.log(child)
            if(child in THREE.Mesh){
                objectss.push(child)
            }
        })

        //射线和模型求交，选中一系列直线
        var intersects = raycaster.intersectObjects( objectss);
        console.log('imtersrcts=' + intersects)

        if (intersects.length > 0) {
            //选中第一个射线相交的物体
           let  SELECTED = intersects[0].object;
            var intersected = intersects[0].object;
            console.log(intersects[0].object)
        }



    }




    function dodiban(){

        let floorGeometry = new PlaneGeometry(1000, 1000, 1);
        let floorMaterial = new MeshPhongMaterial({
           	color: 0x77F28F,
            //   color:  colorArr[colorIndex],
            shininess: 0,
            // wireframe: true
        });
        floor = new Mesh(floorGeometry, floorMaterial);
        floor.rotation.x = -0.5 * Math.PI;
        floor.position.y = -2.1;

        // 地板接受阴影开启
        floor.receiveShadow = true;
        scene.add(floor);
    }


    // 点击部件
    function  dobujian(gltf){
        console.log("点击部件")
        let raycaster = new THREE.Raycaster();

        let mouse = new THREE.Vector2();

        const selectHandler = function (ev) {
            mouse.x = (ev.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(ev.clientY / window.innerHeight) * 2 + 1;

            raycaster.setFromCamera(mouse, camera);

            // 这里我们只检测模型的选中情况
            let intersects = raycaster.intersectObjects(gltf.scene.children, true);


            if (intersects.length > 0) {
             //   console.log(intersects)
                let selectedObjects = intersects[0].object;
                changecolor(selectedObjects)
            }
        }


        let composer = new EffectComposer(renderer);
        let renderPass = new RenderPass(scene, camera);
        composer.addPass(renderPass);

        let outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
        composer.addPass(outlinePass);


        const render = function () {
            requestAnimationFrame(render);
            composer.render();
        }

        outlinePass.visibleEdgeColor.set('#130AF2'); // 选中颜色
        outlinePass.edgeStrength = 5;
        outlinePass.edgeGlow = 1.5;

        document.body.addEventListener('click', selectHandler, false);
    }


    function changecolor(selectedObjects){
        let newMaterial = selectedObjects.material.clone();

        let oldMaterialObj  = selectedObjects.material.clone();


        console.log("objjjjjjjjjjj")
        console.log(selectedObjects)
        let color = newMaterial.color
        console.log(color)
        console.log(newMaterial)
        if(oldSelect && oldMaterial){
            console.log( oldMaterial )
            if(oldSelect.uuid == selectedObjects.uuid){
                console.log("龍王廟")
                newMaterial = oldMaterial
           //     newMaterial.color
                console.log(  newMaterial.color )
                oldMaterial = ''
                oldSelect = ''
            }else{

                oldSelect.material = oldMaterial
                oldMaterial = ''
                oldSelect = ''
                oldSelect =  selectedObjects
                oldMaterial = oldMaterialObj
                console.log("第2次點擊")
                newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
                console.log(  newMaterial.color )
            }

        }else{
            oldSelect =  selectedObjects
            oldMaterial = oldMaterialObj
            console.log("第一次點擊")
            newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
            console.log(  newMaterial.color )
        }
        let html ="<div style='padding: 5px 10px; color: #1b1b1b'>"
        html+="<div >父级UUid:"+selectedObjects.parent.uuid+"</div>"
        html+="<div >父级name:"+selectedObjects.parent.name+"</div>"

        html+="<div >name:"+selectedObjects.name+"</div>"
        html+="<div >uuid:"+selectedObjects.uuid+"</div>"
        html+="</div>"



        $.dialog({
            left:"100%",
            id: 'testID2',
            content: html
        });
        selectedObjects.material = newMaterial;
        render()
    }
    createGUI()

    // 创建ui界面
    function createGUI() {

        if ( gui ) gui.destroy();

        gui = new GUI( { width: 400 } );

        // SHADOW


       let  guiData={
           drawStrokes:true,
           drawFillShapes:4,
           strokesWireframe:true,
           fillShapesWireframe:true,
        }



        gui = new GUI( { width: 350 } );
         gui.addFolder( "Shadow" );

        gui.add( guiData, 'drawStrokes' ).name( 'Draw strokes' ).onChange( update );

        gui.add( guiData, 'drawFillShapes',1,100 ).name( 'Draw fill shapes' ).onChange( update );

        gui.add( guiData, 'strokesWireframe' ).name( 'Wireframe strokes' ).onChange( update );

        gui.add( guiData, 'fillShapesWireframe' ).name( 'Wireframe fill shapes' ).onChange( update );


        function update() {

          $.dialog({
              id:"fff",
              content: "3333333"
          })
        }

    }


    //清理效果
    function cleaningEffect(){


    }


    //内存  帧数 仪表
    function dostats(){
        stats = new Stats();
        document.body.appendChild( stats.dom );

    }

    function render() {
        //  composerAll.render();
        // 主镜头的显示范围
        let w = window.innerWidth
        let h = window.innerHeight
        // 小窗口的显示范围
        let mapHeight = 100
        let mapWidth = 100

        const time = Date.now() * 0.00008;
        renderer.render( scene, camera );
      //  scene.updateMatrixWorld()
        //
        // camera.position.x = Math.sin( time ) * 500;
        // camera.position.z = Math.cos( time ) * 500;
        // camera.lookAt( scene.position );
       // requestAnimationFrame(render)
        stats.update()

    }



</script>

<script src="threejs/js/libs/dat.gui.min.js"></script>
<script>




</script>

</body>
</html>
